﻿using DotNetty.Codecs;
using DotNetty.Handlers.Logging;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using System;
using System.Net;
using System.Threading.Tasks;

namespace TestNettyClient
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var group = new MultithreadEventLoopGroup();
            Console.WriteLine("Hello World!");
            var bootstrap = new Bootstrap();
            bootstrap
                .Group(group)
                .Channel<TcpSocketChannel>()
                .Option(ChannelOption.TcpNodelay, true)
                .Handler(new ActionChannelInitializer<ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    pipeline.AddLast(new LoggingHandler());
                    pipeline.AddLast("framing-encoder", new LengthFieldPrepender(4, true));
                    pipeline.AddLast("framing-decoder", new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, -4, 4));

                    pipeline.AddLast("echo", new EchoClientHandler());
                }));

            IChannel clientChannel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 52013));

            Console.ReadLine();

            await clientChannel.CloseAsync();
            await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
        }
    }
}
